import { defineStore } from 'pinia'
import { ref } from 'vue'
import { login as loginApi } from '@/api/auth'
import { ElMessage } from 'element-plus'

export const useAdminStore = defineStore('admin', () => {
  // 状态
  const token = ref(localStorage.getItem('admin_token') || '')
  const adminInfo = ref(JSON.parse(localStorage.getItem('admin_info') || '{}'))
  
  // 是否已登录
  const isLoggedIn = () => {
    return !!token.value
  }
  
  // 登录
  const login = async (credentials) => {
    try {
      const res = await loginApi(credentials)
      
      if (res.code === 200) {
        const { token: newToken, user } = res.data
        
        // 检查是否为管理员
        if (user.role !== 'admin') {
          ElMessage.error('您没有管理员权限')
          return false
        }
        
        token.value = newToken
        adminInfo.value = user
        
        // 保存到 localStorage
        localStorage.setItem('admin_token', newToken)
        localStorage.setItem('admin_info', JSON.stringify(user))
        
        ElMessage.success('登录成功')
        return true
      } else {
        ElMessage.error(res.message || '登录失败')
        return false
      }
    } catch (error) {
      console.error('登录失败：', error)
      ElMessage.error(error.response?.data?.message || '登录失败')
      return false
    }
  }
  
  // 登出
  const logout = () => {
    token.value = ''
    adminInfo.value = {}
    localStorage.removeItem('admin_token')
    localStorage.removeItem('admin_info')
    ElMessage.success('已退出登录')
  }
  
  return {
    token,
    adminInfo,
    isLoggedIn,
    login,
    logout
  }
})


